import BabelCore, {PluginObj} from "@babel/core";
import {NodePath} from "@babel/traverse";
import {
  ArgumentPlaceholder,
  CallExpression,
  Expression,
  JSXNamespacedName,
  SpreadElement,
  StringLiteral,
  TemplateElement
} from "@babel/types";


function chineseTranscode(args: Array<Expression | SpreadElement | JSXNamespacedName | ArgumentPlaceholder>): string {
  let arg1: string = ''
  let arguments1Element = args[0];
  if (arguments1Element && arguments1Element.type === 'StringLiteral') {
    arg1 = arguments1Element.value
  } else {
    throw "第一个参数错误"
  }
  return arg1
}

function strHasChinese(str: string) {
  let pattern = /[\u4e00-\u9fa5]/
  return pattern.test(str)
}

function replaceWith(t: typeof BabelCore.types, path: NodePath, value: string) {
  const identifier = t.identifier("decodeURIComponent");
  const stringLiteral = t.stringLiteral(encodeURIComponent(value));
  const callExpression = t.callExpression(identifier, [stringLiteral]);
  path.replaceWith(callExpression)
}

export default function (babel: typeof BabelCore): PluginObj {
  let t = babel.types
  return {
    name: "babel-plugin-getFilePath",
    visitor: {
      TemplateElement(path: NodePath<TemplateElement>, state) {
        const node = path.node;
        let raw = node.value.raw;
        if (strHasChinese(raw)) {
          replaceWith(t, path, raw)
        }
      },
      StringLiteral(path: NodePath<StringLiteral>, state) {
        const node = path.node;
        const value = node.value;
        if (strHasChinese(value)) {
          replaceWith(t, path, value)
        }
      },
      CallExpression(path: NodePath<CallExpression>, state) {
        let node = path.node
        let callee = node.callee;
        if (callee.type === 'MemberExpression') {
          const property = callee.property;
          if (property.type === 'Identifier') {
            const name1 = property.name;
            if (name1 === '__chineseTranscode__') {
              // 这里就找到了 window.__chineseTranscode__
              replaceWith(t, path, chineseTranscode(node.arguments))
            }
          }
        } else if (callee.type === 'Identifier') {
          if (callee.name === '__chineseTranscode__') {
            // 找到 __chineseTranscode__
            replaceWith(t, path, chineseTranscode(node.arguments))
          }
        }
      },

    },
  };
}


